<?php
namespace app\agency\controller;
use think\Db;
use clt\Tree;
use think\Request;
use think\Controller;
use qiniu\Qiniu;
class OnlineCourse extends Common
{
    public function _initialize(){
        parent::_initialize();
    }
    //列表页
    public function index(){
        if(request()->isPost()) {
            $key = input('post.key');
            $this->assign('testkey', $key);
            $page =input('page')?input('page'):1;
            $pageSize =input('limit')?input('limit'):config('pageSize');
            $list = Db::name('online_course')
                ->where('course_name', 'like', "%" . $key . "%")
                ->order('sort DESC')
                ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                ->toArray();
            foreach ($list['data'] as $k=>$v){
                $list['data'][$k]['addtime'] = date('Y-m-d H:s',$v['addtime']);
            }
            return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }
        return $this->fetch();
    }

    //获取发布栏目
    public function getCat(){
        if(request()->isAjax()){
            $key = input('post.key');
            $this->assign('testkey', $key);
            $catlsit = db('category')
                ->where('name', 'like', "%" . $key . "%")
                ->field('cate_id,name,parent_id')
                ->select();
            $tree = new Tree ($catlsit);
            //p($catlsit);
            $categorys = $tree->recursion(0);
            $nbsp="&nbsp;&nbsp;&nbsp;&nbsp;";
            $str = "";
            foreach($categorys as $k=>$v){
                $str.="<h3><a href='javascript:;' data-id='{$v['cate_id']}' data-name='{$v['name']}'>{$v['name']}</a></h3>";
                if(is_array($v['son'])){
                    $str.="<p>";
                    foreach($v['son'] as $k1=>$v1){
                        $str.="&nbsp;&nbsp;&nbsp;├─&nbsp; <a href='javascript:;' data-id='{$v1['cate_id']}' data-name='{$v1['name']}'>{$v1['name']}</a>{$nbsp}";
                        if(is_array($v1['son'])){
                            $str.="<p>";
                            foreach($v1['son'] as $k2=>$v2){
                                $str.="<a href='javascript:;' data-id='{$v2['cate_id']}' data-name='{$v2['name']}'>&nbsp;&nbsp;&nbsp;├─&nbsp;├─&nbsp; {$v2['name']}{$nbsp}</a>";
                            }
                            $str.="</p>";
                        }
                    }
                    $str.="</p>";
                }
            }
            //$this->assign('actList',$str);
            echo $str;
        }else{
            $catlsit = db('category')
                ->field('cate_id,name,parent_id')
                ->select();
            $tree = new Tree ($catlsit);
            $categorys = $tree->recursion(0);
            $nbsp="&nbsp;&nbsp;&nbsp;&nbsp;";
            $str = "";
            foreach($categorys as $k=>$v){
                $str.="<h3><a href='javascript:;' data-id='{$v['cate_id']}' data-name='{$v['name']}'>{$v['name']}</a></h3>";
                if(is_array($v['son'])){
                    $str.="<p>";
                    foreach($v['son'] as $k1=>$v1){
                        $str.="&nbsp;&nbsp;&nbsp;├─&nbsp; <a href='javascript:;' data-id='{$v1['cate_id']}' data-name='{$v1['name']}'>{$v1['name']}</a>{$nbsp}";
                        if(is_array($v1['son'])){
                            $str.="<p>";
                            foreach($v1['son'] as $k2=>$v2){
                                $str.="<a href='javascript:;' data-id='{$v2['cate_id']}' data-name='{$v2['name']}'>&nbsp;&nbsp;&nbsp;├─&nbsp;├─&nbsp; {$v2['name']}{$nbsp}</a>";
                            }
                            $str.="</p>";
                        }
                    }
                    $str.="</p>";
                }
            }
            $this->assign('actList',$str);
            return $this->fetch();
        }
    }


    //数据添加
    public function add(){
        if(request()->isPost()) {
            //构建数组
            $data = input('post.');

            $data['addtime'] = time();    //添加时间
            $data['status'] = 0;           //状态,默认待审核
            $data['agency_id'] = session('agency_id');  //机构ID
            $data['addtime'] = time();     //添加时间
            $data['course_sn'] = 'kc_'.date('YmdHis',time()).rand_string('3',1);     //课程编号



            //通过提交过的栏目ID,获取其家族路径
            $parent_id_path = db('category')->where('cate_id',$data['cat_id'])->value('parent_id_path');
            $path_arr = explode(',',$parent_id_path);

            if(is_array($path_arr)){
                if($path_arr[1] > 0 ){
                    $data['cat_id1'] = $path_arr[1];   //一级类别id
                }

                if($path_arr[2] > 0 ){
                    $data['cat_id2'] = $path_arr[2];   //二级类别id
                }

                if($path_arr[3] > 0 ){
                    $data['cat_id3'] = $path_arr[3];    //三级类别id
                }
            }
            $row =  db('online_course')->insert($data);     //添加数据
            $userId = db('online_course')->getLastInsID();

            if($row > 0 ){
                $result['code'] = 1;
                $result['msg'] = '课程添加成功,等待后台审核';
                $result['url'] = url('edit',array('course_id'=>$userId));
            }else{
                $result['code'] = 0;
                $result['msg'] = '操作失败';
                $result['url'] = url('add');
            }

            return $result;
        }else{


            //$this->assign('adtypeList',json_encode($adtypeList,true));

            $this->assign('title','添加课程');
            $this->assign('info','null');
            return $this->fetch('form');
        }
    }

    //数据修改
    public function edit(){
        if(request()->isPost()) {
            $data = input('post.');

            //通过提交过的栏目ID,获取其家族路径
            $parent_id_path = db('category')->where('cate_id',$data['cat_id'])->value('parent_id_path');
            $path_arr = explode(',',$parent_id_path);

            if(is_array($path_arr)) {
                if ($path_arr[1] > 0) {
                    $data['cat_id1'] = $path_arr[1];   //一级类别id
                }

                if ($path_arr[2] > 0) {
                    $data['cat_id2'] = $path_arr[2];   //二级类别id
                }

                if ($path_arr[3] > 0) {
                    $data['cat_id3'] = $path_arr[3];    //三级类别id
                }
            }
            $row = db('online_course')->update($data);

            $result['code'] = 1;
            $result['msg'] = '课程修改成功!';
            $result['url'] = url('index');
            return $result;
        }else{

            $course_id=input('course_id');
            //1.查询课程信息
            $adInfo=db('online_course')->where(array('course_id'=>$course_id))->find();

            //2.查询关联的栏目名称
            if($adInfo['cat_id3'] > 0){
                $catInfo = db('category')->field('cate_id,name')->where('cate_id',$adInfo['cat_id3'])->find();
            }else if($adInfo['cat_id2'] > 0){
                $catInfo = db('category')->field('cate_id,name')->where('cate_id',$adInfo['cat_id2'])->find();
            }else if($adInfo['cat_id1'] > 0){
                $catInfo = db('category')->field('cate_id,name')->where('cate_id',$adInfo['cat_id1'])->find();
            }

            $this->assign('info',json_encode($adInfo,true));
            $this->assign('catInfo',$catInfo);
            $this->assign('title',lang('edit').'课程');
            $this->assign('course_id',$course_id);
            return $this->fetch('form');
        }
    }

    //修改状态
    public function editState(){
        $id=input('post.id');
        $open=db('online_course')->where(array('course_id'=>$id))->value('open');//判断当前状态情况
        if($open==1){
            $data['open'] = 0;
            db('online_course')->where(array('course_id'=>$id))->setField($data);
            $data['status'] = 1;
        }else{
            $data['open'] = 1;
            db('online_course')->where(array('course_id'=>$id))->setField($data);
            $data['status'] = 1;
        }
        return $data;
    }

    //修改排序
    public function adOrder(){
        $course=db('online_course');
        $data = input('post.');
        if($course->update($data)!==false){
            return $result = ['msg' => '操作成功！','url'=>url('index'), 'code' =>1];
        }else{
            return $result = ['code'=>0,'msg'=>'操作失败！'];
        }
    }


    //单条数据删除
    public function del(){
        db('online_course')->where(array('course_id'=>input('course_id')))->delete();
        return ['code'=>1,'msg'=>'删除成功！'];
    }

    //数据批量删除
    public function delall(){
        $map['course_id'] =array('in',input('param.ids/a'));
        db('online_course')->where($map)->delete();
        $result['msg'] = '删除成功！';
        $result['code'] = 1;
        $result['url'] = url('index');
        return $result;
    }

    /********************************   课详情操作 start  **********************************************/
    //详情列表
    public function dateilList(){
        $course_id=input('course_id');

        //先查个一级章节
        $where['course_id'] = array('eq',$course_id);
        $where['pid'] = array('eq',0);
        $list = db('online_course_detail')->where($where)->order('sort')->select();

        //查询子级列表
        foreach($list as $k => $v){
            $list[$k]['son'] = db('online_course_detail')->where('pid',$v['course_detail_id'])->order('sort')->select();
        }

        $course_name = db('online_course')->where('course_id',$course_id)->value('course_name');  //获取课程名称

        $nbsp = "&nbsp;&nbsp;┠┈";
        $this->assign('nbsp',$nbsp);
        $this->assign('course_name',$course_name);  //获取课程名称
        $this->assign('list',$list);
        $this->assign('course_id',$course_id);
        return  $this->fetch();
    }

    //添加课程详情内容
    public function addDateil(){
        $course_id = input('course_id');
        if(request()->isPost()){
            $data = input('post.');
            $pid =$data['pid'];

            //判断是音频流还是视频流
            if(!empty($data['aurl'])){
                $data['url'] = $data['aurl'];
                $data['type'] = 2;
            }else{
                $data['url'] = $data['vurl'];
                $data['type'] = 1;
            }

            if($pid >=0 && $pid != null){
                $data['pid'] = $pid;
            }else{
                $data['pid'] = 0 ;
            }

            $row = db('online_course_detail')->insert($data);

            if($row > 0 ){
                $result['code'] = 1;
                $result['msg'] = '添加成功';
                $result['url'] = url('dateilList',array('course_id'=>$course_id));
            }else{
                $result['code'] = 0;
                $result['msg'] = '添加失败';
                $result['url'] = url('dateilList',array('course_id'=>$course_id));
            }

            return $result;
        }else{
            //获取当前课程的一级栏目
            $where['pid'] = array('eq',0);
            $where['course_id'] = array('eq',$course_id);
            $catList = db('online_course_detail')->field('course_detail_id,name')->where($where)->select();

            //组装一个默认数组
            $pid= input('pid')?intval(input('pid')):0;
            $this->assign('catList',$catList);
            $this->assign('info','null');
            $this->assign('pid',$pid);
            $this->assign('course_id',$course_id);
            return  $this->fetch('formDatail');
        }
    }

    //修改课程章节数据
    public function editDateil(){
        $course_id = input('course_id');
        if(request()->isPost()){
            $data = input('post.');
            $pid =$data['pid'];
            if($pid >=0 && $pid != null){
                $data['pid'] = $pid;
            }else{
                $data['pid'] = 0 ;
            }

            //判断是音频流还是视频流
            if(!empty($data['aurl'])){
                $data['url'] = $data['aurl'];
                $data['type'] = 2;
            }else{
                $data['url'] = $data['vurl'];
            }

            $row = db('online_course_detail')->insert($data);

            if($row > 0 ){
                $result['code'] = 1;
                $result['msg'] = '修改成功';
                $result['url'] = url('dateilList',array('course_id'=>$course_id));
            }else{
                $result['code'] = 0;
                $result['msg'] = '修改失败';
                $result['url'] = url('dateilList',array('course_id'=>$course_id));
            }

            return $result;
        }else{
            //获取当前课程的一级栏目
            $where['pid'] = array('eq',0);
            $where['course_id'] = array('eq',$course_id);
            $catList = db('online_course_detail')->field('course_detail_id,name')->where($where)->select();

            //查询当前要修改的数据
            $course_detail_id = input('course_detail_id');
            $info = db('online_course_detail')->where('course_detail_id',$course_detail_id)->find();
            $this->assign('catList',$catList);
            $this->assign('pid',$info['pid']);
            $this->assign('edit','edit');
            $this->assign('infos',$info);
            $this->assign('info',json_encode($info,true));
            $this->assign('course_id',$course_id);
            return  $this->fetch('formDatail');
        }
    }

    //删除操作
    public function delDateil(){
        $data = input('post.');

        //先通过章节
        $where['pid'] = array('eq',$data['course_detail_id']);
        $where['course_id'] = array('eq',$data['course_id']);
        db('online_course_detail')->where($where)->delete();

        $row = db('online_course_detail')->where($data)->delete();

        if($row > 0 ){
            $data = array(
                'code'=>  1,
                'msg'=> '删除成功',
                'url' => url('dateilList',array('course_id'=>$data['course_id']))
            );
        }else{
            $data = array(
                'code'=>  0,
                'msg'=> '删除失败',
            );
        }

        return $data;

    }

    //修改详情列表排序
    public function deitOrder(){
        $data = input('post.');

        $row = db('online_course_detail')->update($data);

        if($row > 0 ){
            $data = array(
                'code'=> 1 ,
                'msg'=> '排序成功',
                'url' => url('dateilList',array('course_id'=>$data['course_id']))
            );
        }else{
            $data = array(
                'code'=> 1 ,
                'msg'=> '排序失败',
                'url' => url('dateilList',array('course_id'=>$data['course_id']))
            );
        }

        return json($data);
    }

    //修改课程详情状态
    public function editStatus(){
        $data = input('post.');

        if($data['status'] == 'true'){
            $data['status'] = 1;
            $row = db('online_course_detail')->update($data);
        }else{
            $data['status'] = 0;
            $row = db('online_course_detail')->update($data);
        }

        if($row > 0 ){
            $data = array(
                'code'=> 1 ,
                'msg'=> '操作成功',
            );
        }else{
            $data = array(
                'code'=> 1 ,
                'msg'=> '操作失败',
            );
        }

        return json($data);
    }

    //修改课程详情状态
    public function isPreview(){
        $data = input('post.');
        if($data['is_preview'] == 'true'){
            $data['is_preview'] = 1;
            $row = db('online_course_detail')->update($data);
        }else{
            $data['is_preview'] = 0;
            $row = db('online_course_detail')->update($data);
        }

        if($row > 0 ){
            $data = array(
                'code'=> 1 ,
                'msg'=> '操作成功',
            );
        }else{
            $data = array(
                'code'=> 1 ,
                'msg'=> '操作失败',
            );
        }

        return json($data);
    }

    //上传资源到七牛云
    public function upQiniu(){
        set_time_limit(1800);  //设定上传时间
        // 获取上传文件表单字段名
        $fileKey = array_keys(request()->file());

        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file($fileKey['0']);

        $res = Qiniu::upload($file); //上传到七牛

        if($res == 1){
            // 上传失败获取错误信息
            $result['code'] =0;
            $result['info'] = '图片上传失败!';
            $result['url'] = '';
        }else{
            $result['code'] = 1;
            $result['info'] = '图片上传成功!';
            $result['url'] = 'http://p8jq3mb78.bkt.clouddn.com/'.$res['key'];
        }
        return json($result);
    }
}